import os
import json
from neo4j import GraphDatabase

# Neo4j 连接配置
URI = "bolt://localhost:7687"  # Neo4j 服务器地址
AUTH = ("neo4j",  "Dfitc@123")   # 用户名和密码

# 遍历读取 data 目录下的所有 JSON 文件
data = []
data_dir = './vue'
for root, dirs, files in os.walk(data_dir):
    for file in files:
        if file.endswith('.json'):
            file_path = os.path.join(root, file)
            with open(file_path, 'r', encoding='utf-8') as f:
                json_data = json.load(f)
                data.extend(json_data)

# 插入数据到 Neo4j
def insert_data_to_neo4j(data):
    # 连接到 Neo4j
    driver = GraphDatabase.driver(URI, auth=AUTH)

    with driver.session() as session:
        for entry in data:
            function_name = entry["function"]
            tables = entry["table"]

            # 创建 Function 节点
            session.run(
                """
                MERGE (f:Operation {name: $function_name})
                """,
                function_name=function_name
            )

            for table in tables:
                table_name = table["name"]
                relation = table["relation"]
                columns = table["columns"]

                # 创建 Table 节点
                session.run(
                    """
                    MERGE (t:RequestMapping {name: $table_name})
                    """,
                    table_name=table_name
                )

                # 创建 Function 和 Table 之间的关系
                session.run(
                    """
                    MATCH (f:Operation {name: $function_name})
                    MATCH (t:RequestMapping {name: $table_name})
                    MERGE (f)-[r:QUERIES {relation: $relation}]->(t)
                    """,
                    function_name=function_name,
                    table_name=table_name,
                    relation=relation
                )

                # 为 Table 节点添加列属性
                session.run(
                    """
                    MATCH (t:RequestMapping {name: $table_name})
                    SET t.columns = $columns
                    """,
                    table_name=table_name,
                    columns=columns
                )

    # 关闭连接
    driver.close()

# 执行插入操作
insert_data_to_neo4j(data)
print("数据已成功插入到 Neo4j 中！")
